require 'openssl'
require 'digest'
module PayrollService
	def self.create_payroll
		project_users = ProjectUser.where("join_time IS NOT NULL AND exit_time IS NULL")
		project_users.each do |pu|
			time = Time.new 
			last_month = time.month - 1
			year = time.year
			### 需要判断上班卡下班卡是否齐全 ### 
			sign = Sign.where(user_id: pu.user_id, project_id: pu.project_id, year: year, month: last_month)
			if pu.pay.nil?
				payroll_month = sign.size * 2000
			else
				payroll_month = sign.size * pu.pay.to_i
			end
			
			payroll_name = year.to_s + "年-" + last_month.to_s + "月:" + "工资单"
			payroll = Payroll.where(project_id: pu.project_id, payroll_name: payroll_name).first
			if payroll.nil?
				payroll = Payroll.new
				payroll.payroll_name = payroll_name
				payroll.project_id = pu.project_id
				payroll.save
				payroll_detail = PayrollDetail.new
				payroll_detail.payroll_id = payroll.id
				payroll_detail.project_user_id = pu.id
				payroll_detail.work_days = sign.size
				payroll_detail.totalPayAmount = payroll_month
				payroll_detail.actualAmount = payroll_month
				payroll_detail.payroll_status = 0
				payroll_detail.created_at = Time.now
				payroll_detail.updated_at = Time.now
				payroll_detail.save
			else
				payroll_detail = PayrollDetail.new
				payroll_detail.payroll_id = payroll.id
				payroll_detail.project_user_id = pu.id
				payroll_detail.work_days = sign.size
				payroll_detail.totalPayAmount = payroll_month
				payroll_detail.actualAmount = payroll_month
				payroll_detail.payroll_status = 0
				payroll_detail.created_at = Time.now
				payroll_detail.updated_at = Time.now
				payroll_detail.save
			end
		end
	end
end